<?php

// +----------------------------------------------------------------------
// | H1CMS © OpenSource CMS
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2016 http://www.h1cms.com All rights reserved.
// | Copyright (c) 2014-2016 嘉兴领格信息技术有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Allen <allen@lg4.cn>
// +----------------------------------------------------------------------

use Lg\Security\Password;
use h1cms\model\User;
use h1cms\system\Auth;
use Lg\Database\DB;

function user_login($username, $password) {
    if (Lg\Support\Validator::isEmail($username)) {
        $condition = ['email' => $username];
    } else {
        $condition = ['username' => $username];
    }
    $user = User::findOne($condition);

    if ($user && $user->status == 1 && Password::verify($password, $user->password)) {
        $roles = DB::getCol('select role_id from {user_roles} where uid=:uid', ['uid' => $user->id]);
        Auth::login($user, $roles, in_array(1, $roles));
//        $user->updated_at = time();
        $user->lasttime = time();
        $user->lastip = \Lg\Http\Input::req()->ip();
        $user->save();
        return true;
    }
    return false;
}
